//
//  KLOpenLockHistoryTableViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/8/18.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLOpenLockHistoryTableViewController.h"
#import "KLHttpAPI.h"
#import "KLHelp.h"
#import "HemaConst.h"
#import "JRToast.h"
#import "Masonry.h"
#import "HemaFunction.h"
#import "JRToast.h"
#import "UIView+MJExtension.h"
#import "MJRefresh.h"

static int freshTimes;

@interface KLOpenLockHistoryTableViewController ()
{
    NSArray *refreshArr;//开锁历史记录每次的返回数据
    NSMutableArray *allListArr;//数据源
    
    UISegmentedControl *segContontrol;
}
@property(nonatomic,strong) NSArray *commandList;//命令列表记录
@end

@implementation KLOpenLockHistoryTableViewController
-(NSArray *)commandList{
    if(!_commandList){
        _commandList = [NSArray array];
    }
    return _commandList;
}

-(void)viewWillAppear:(BOOL)animated{
    freshTimes = 1;
    allListArr = [NSMutableArray array];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self naveSet];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self refreshOpenLockHistory];
    }];
    
    // 马上进入刷新状态
    [self.tableView.mj_footer beginRefreshing];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(segContontrol.selectedSegmentIndex == 0)
        return allListArr.count;
    else
        return self.commandList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"openLockHistory"];
    if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"openLockHistory"];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil){
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    
    NSDictionary *dic;
    if(segContontrol.selectedSegmentIndex == 0){
        dic = [NSDictionary dictionaryWithDictionary:allListArr[indexPath.row]];
    }else{
        dic = [NSDictionary dictionaryWithDictionary:self.commandList[indexPath.row]];
    }
    UILabel *openTime = [[UILabel alloc]init];
    openTime.textAlignment = NSTextAlignmentLeft;
    openTime.font = [UIFont systemFontOfSize:16];
    [cell.contentView addSubview:openTime];
    [openTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(5);
        make.left.mas_equalTo(5);
    }];
    
    UILabel *openState = [[UILabel alloc]init];
    openState.textAlignment = NSTextAlignmentLeft;
    openState.font = [UIFont systemFontOfSize:13];
    openState.textColor = RGB_UI_COLOR(150, 150, 150);
    [cell.contentView addSubview:openState];
    [openState mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(openTime).with.offset(25);
        make.left.mas_equalTo(5);
    }];
    
    UILabel *openUserName = [[UILabel alloc]init];
    NSString *mobile = [dic objectForKey:@"mobile"];
    openUserName.textAlignment = NSTextAlignmentLeft;
    openUserName.font = [UIFont systemFontOfSize:13];
    openUserName.textColor = RGB_UI_COLOR(150, 150, 150);
    [cell.contentView addSubview:openUserName];
    [openUserName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(cell.contentView).with.offset(-5);
        make.left.mas_equalTo(5);
    }];
    
    if(segContontrol.selectedSegmentIndex == 0){
        openTime.text = [NSString stringWithFormat:@"开锁时间:%@",[dic objectForKey:@"openlock_time"]];
        openState.text = [NSString stringWithFormat:@"开锁状态:%@",[dic objectForKey:@"lockstate"]];
        if([mobile isEqualToString:@"00000000000"]){
            openUserName.text = [NSString stringWithFormat:@"开锁用户:%@",[dic objectForKey:@"username"]];
        }else{
            openUserName.text = [NSString stringWithFormat:@"开锁用户:%@  %@",[dic objectForKey:@"username"],mobile];
        }
    }else{
        openTime.text = [NSString stringWithFormat:@"锁别名:%@",[dic objectForKey:@"name"]];
        openState.text = [NSString stringWithFormat:@"地址:%@",[dic objectForKey:@"address"]];
        openUserName.text = [NSString stringWithFormat:@"发送给用户:%@",[dic objectForKey:@"receiver"]];
        
        UILabel *commandName = [[UILabel alloc]init];
        commandName.textColor = RGB_UI_COLOR(74, 134, 232);
        commandName.font = [UIFont systemFontOfSize:15];
        [cell.contentView addSubview:commandName];
        [commandName mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15);
            make.top.mas_equalTo(10);
        }];
        NSString *type = [dic objectForKey:@"type"];
        switch (type.integerValue) {
            case 0:
                commandName.text = @"校时";
                break;
            case 1:
                commandName.text = @"设置黑名单";
                break;
            case 2:
                commandName.text = @"取消黑名单";
                break;
            default:
                break;
        }
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 73;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -界面设置
//初始化导航栏
-(void)naveSet{
//    self.title = @"开锁历史记录";
    // 设置导航条的titleView内容
    segContontrol = [[UISegmentedControl alloc] initWithItems:@[@"开锁历史记录",@"委托历史记录"]];
    [segContontrol setTintColor:RGB_UI_COLOR(0, 204, 102)];
    // 设置选中的文字颜色
    [segContontrol setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateSelected];
    segContontrol.selectedSegmentIndex = 0;
    //设置分段控件点击相应事件
    [segContontrol addTarget:self action:@selector(changeList:)forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = segContontrol;
    
    self.view.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}-(void)changeList:(UISegmentedControl *)segmentControl{
    if(segmentControl.selectedSegmentIndex == 1){
        [self getAllCommandHistoryList];
    }else{
        [self.tableView reloadData];
    }
}

#pragma mark - 刷新获取历史记录列表
-(void)refreshOpenLockHistory{
    [KLHttpAPI requestOpenLockHistroryWithLockID:[self.currentLockInfo objectForKey:@"id"] page_num:[NSString stringWithFormat:@"%d",freshTimes] completionHandler:^(MKNetworkOperation *operation) {
        
        NSLog(@"＊＊＊＊＊＊＊page_num:%@＊＊＊＊＊＊＊＊＊ %@",[NSString stringWithFormat:@"%d",freshTimes],operation.responseString);
        refreshArr = [NSArray arrayWithArray:[operation.responseJSON objectForKey:@"infor"]];
        [allListArr addObjectsFromArray:refreshArr];
        if(refreshArr.count == 0){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            // 马上结束刷新状态
            [self.tableView.mj_footer endRefreshing];
            freshTimes++;
        }
        
        if(allListArr.count == 0){
            [KLHelp setNoDateImageWithView:self.view type:0];
        }else{
            [KLHelp removeImgViewAndNoticeLabel];
        }
        [self.tableView reloadData];
    } errorHandler:^(NSString *error) {
    }];
}

#pragma mark - 获取历史委托命令列表
-(void)getAllCommandHistoryList{
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI getAllCommandHistoryWithLock_id:[self.currentLockInfo objectForKey:@"id"] completionHandler:^(MKNetworkOperation *operation) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSLog(@"＊＊＊＊＊＊＊page_num:%@＊＊＊＊＊＊＊＊＊ %@",[NSString stringWithFormat:@"%d",freshTimes],operation.responseString);
        NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            self.commandList = [NSArray arrayWithArray:[operation.responseJSON objectForKey:@"msg"]];
            
            if(self.commandList.count == 0){
                [KLHelp setNoDateImageWithView:self.view type:0];
            }else{
                [KLHelp removeImgViewAndNoticeLabel];
            }
//            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            [self.tableView reloadData];
        }else{
            [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"infor"]];
        }
    } errorHandler:^(NSString *error) {
        [KLHelp showTextHUDforView:self.view text:error];
    }];
}
@end
